<!-- 商品详情页面 -->
<template>
    <div class="product-detail">
        <div class="product-container">
            <!-- 左侧商品展示区 -->
            <div class="product-gallery">
                <div class="main-image" @click="openGallery">
                    <el-image 
                        :src="currentImage && !currentImage.startsWith('http') ? '/images/product/' + currentImage : currentImage" 
                        fit="cover"
                        :preview-src-list="product.images.map(img => img && !img.startsWith('http') ? '/images/product/' + img : img)"
                        :initial-index="currentImageIndex"
                        class="gallery-image"
                    />
                    <div class="zoom-hint">
                        <el-icon><ZoomIn /></el-icon>
                        <span>点击查看大图</span>
                    </div>
                </div>
                
                <div class="thumbnail-nav">
                    <div 
                        v-for="(image, index) in product.images" 
                        :key="index"
                        class="thumbnail"
                        :class="{ active: currentImageIndex === index }"
                        @click="currentImageIndex = index"
                    >
                        <el-image :src="image && !image.startsWith('http') ? '/images/product/' + image : image" fit="cover" />
                    </div>
                </div>
            </div>

            <!-- 右侧信息区 -->
            <div class="product-info">
                <div class="product-header">
                    <h1 class="product-title">{{ product.name }}</h1>
                    <el-tag 
                        :type="product.condition === '全新' ? 'success' : 'warning'"
                        class="condition-tag"
                    >
                        {{ product.condition || '未知' }}
                    </el-tag>
                </div>

                <div class="product-meta">
                    <div class="product-price">¥{{ product.price?.toFixed(2) || '0.00' }}</div>
                    <div class="product-original-price" v-if="product.originalPrice && product.originalPrice > product.price">
                        原价 ¥{{ product.originalPrice.toFixed(2) }}
                    </div>
                </div>

                <div class="status-section">
                    <el-tag 
                        :type="product.status === 'selling' ? 'success' : 'danger'"
                        class="status-tag"
                    >
                        {{ product.status === 'selling' ? '在售' : '已售出' }}
                    </el-tag>
                    <span v-if="product.stock" class="stock-info">
                        库存: {{ product.stock }}件
                    </span>
                </div>

                <div class="product-description">
                    <h3 class="description-title">商品描述</h3>
                    <p :class="{ 'collapsed': !showFullDescription }">
                        {{ product.description || '暂无描述' }} 
                    </p>
                    <div 
                        v-if="(product.description || '').length > 100" 
                        class="show-more"
                        @click="showFullDescription = !showFullDescription"
                    >
                        {{ showFullDescription ? '收起' : '查看更多' }}
                        <el-icon>
                            <component :is="showFullDescription ? 'ArrowUp' : 'ArrowDown'" />
                        </el-icon>
                    </div>
                </div>

                <!-- 卖家信息卡片 -->
                <div class="seller-card">
                    <div class="seller-info">
                        <el-avatar 
                            :size="48" 
                            :src="seller.avatar && !seller.avatar.startsWith('http') ? '/images/user/' + seller.avatar : seller.avatar"
                            class="seller-avatar"
                        />
                        <div class="seller-details">
                            <div class="seller-name">{{ seller.name }}</div>
                            <div class="seller-school">{{ seller.school }}</div>
                        </div>
                        <div class="seller-rating">
                            <el-rate
                                v-model="seller.rating"
                                disabled
                                show-score
                                text-color="#ff9900"
                                score-template="{value}"
                            />
                        </div>
                    </div>
                    <div class="seller-actions">
                        <el-button type="primary" @click="contactSeller">
                            <el-icon><Message /></el-icon>
                            联系卖家
                        </el-button>
                        <el-button @click="followSeller">
                            <el-icon><Star /></el-icon>
                            关注Ta
                        </el-button>
                    </div>
                </div>

                <!-- 购买操作区 -->
                <div class="purchase-section">
                    <div class="action-buttons">
                        <el-button 
                            type="primary" 
                            class="add-to-cart"
                            @click="addToCart"
                        >
                            加入购物车
                        </el-button>
                        <el-button 
                            type="primary" 
                            class="buy-now"
                            @click="buyNow"
                        >
                            立即购买
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 推荐区域 -->
        <div class="recommendations">
            <h2 class="section-title">猜你喜欢</h2>
            <div class="recommendation-grid">
                <div 
                    v-for="item in recommendations" 
                    :key="item.id"
                    class="recommendation-card"
                    @click="goToProduct(item.id)"
                >
                    <el-image :src="item.image && !item.image.startsWith('http') ? '/images/product/' + item.image : item.image" fit="cover" />
                    <div class="recommendation-info">
                        <div class="recommendation-name">{{ item.name }}</div>
                        <div class="recommendation-price">¥{{ item.price }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 订单创建弹窗 -->
    <OrderCreateDialog 
        :visible="orderDialogVisible"
        @update:visible="orderDialogVisible = $event"
        :product-info="product"
        @order-created="handleOrderCreated"
    />
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import request from '@/utils/request'
import { 
    Message, 
    Star, 
    ZoomIn,
    ArrowUp,
    ArrowDown 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createConversation } from '../../api/chat'
import OrderCreateDialog from '@/components/order/OrderCreateDialog.vue'

const router = useRouter()
const route = useRoute() // 获取当前路由
const currentImageIndex = ref(0)
const quantity = ref(1) // 保留变量但不再提供UI修改
const showFullDescription = ref(false)
const loading = ref(false) // 添加加载状态

// 定义接口
interface ProductImage {
    url: string;
    // 可以根据需要添加其他属性，如 alt 文本等
}

interface Product {
    id: number;
    name: string;
    price: number;
    originalPrice?: number;
    condition?: string;
    status: string; // 'selling', 'sold', 'off_shelf' 等
    stock?: number;
    description?: string;
    images: string[]; // 修改为 string[]
    mainImageUrl?: string; // 添加 mainImageUrl
    sellerId?: number;
    sellerName?: string;
    sellerAvatar?: string;
    categoryId?: number;
    categoryName?: string;
    locationDescription?: string;
    views?: number;
    favoriteCount?: number;
    isFavorite?: boolean;
    [key: string]: any; // 允许其他未知属性
}

interface Seller {
    id: number;
    name: string;
    school?: string;
    avatar?: string;
    rating?: number;
}

interface RecommendationItem {
    id: number;
    name: string;
    price: number;
    image: string;
    // 根据需要添加其他属性
}

// 商品数据，初始为空
const product = ref<Product>({ // 使用 Product 接口
    id: 0,
    name: '',
    price: 0,
    originalPrice: 0,
    condition: '',
    status: 'selling',
    stock: 1,
    description: '',
    images: [] // 初始化为 string[]
})

// 卖家数据
const seller = ref<Seller>({ // 使用 Seller 接口
    id: 0,
    name: '',
    school: '',
    avatar: 'https://picsum.photos/100/100', // 默认头像
    rating: 5
})

// 推荐商品
const recommendations = ref<RecommendationItem[]>([]) // 使用 RecommendationItem[] 接口

// 新增订单弹窗变量
const orderDialogVisible = ref(false)

// 从localStorage获取商品数据
const loadProductDataFromLocalStorage = () => {
    const storedData = localStorage.getItem('currentProductDetail')
    if (storedData) {
        try {
            const productDetail = JSON.parse(storedData)
            
            // 检查ID是否匹配
            if (productDetail.id === Number(route.params.id)) {
                updateProductData(productDetail)
                
                // 获取卖家信息
                if (productDetail.sellerId) {
                    fetchSellerInfo(productDetail.sellerId)
                } else if (productDetail.seller && productDetail.seller.id) {
                    fetchSellerInfo(productDetail.seller.id)
                }
                
                // 获取推荐商品
                fetchRecommendations(productDetail.id, productDetail.categoryId)
                
                console.log('商品数据已从localStorage加载');
                return true // 表示成功从localStorage加载
            } else {
                // ID不匹配，清除旧数据
                localStorage.removeItem('currentProductDetail')
                console.log('localStorage中的商品ID与当前页面ID不匹配，已清除旧数据');
            }
        } catch (error) {
            console.error('解析localStorage中的商品数据失败:', error)
            localStorage.removeItem('currentProductDetail') // 解析失败则清除
        }
    }
    return false // 未从localStorage加载或加载失败
}

// 从后端API获取商品数据
const fetchProductData = async () => {
    loading.value = true
    const productId = Number(route.params.id)

    if (!productId) {
        ElMessage.error('无效的商品ID')
        loading.value = false
        // 可以选择跳转到错误页或首页
        router.push('/')
        return
    }
    
    console.log('开始获取商品数据, ID:', productId)
    
    try {
        // 尝试从API获取商品详情
        const response = await request.get(`/products/${productId}`)
        console.log('获取商品详情响应:', response)
        
        if (response && (response.code === 200 || response.status === 200) && response.data) {
            const productDetail = response.data
            updateProductData(productDetail)
            
            // 存储到localStorage
            localStorage.setItem('currentProductDetail', JSON.stringify(productDetail))
            
            // 获取卖家信息
            if (productDetail.sellerId) {
                fetchSellerInfo(productDetail.sellerId)
            } else if (productDetail.seller && productDetail.seller.id) {
                fetchSellerInfo(productDetail.seller.id)
            }
            
            // 获取推荐商品
            fetchRecommendations(productId, productDetail.categoryId)

        } else {
            ElMessage.error(response?.message || '获取商品详情失败')
            console.warn('商品详情获取失败或数据为空，尝试使用模拟数据');
            useDefaultMockData(); // 获取失败时使用模拟数据
        }
    } catch (error) {
        console.error('获取商品数据出错:', error)
        ElMessage.error('获取商品数据失败，请稍后重试')
        useDefaultMockData(); // 异常时也使用模拟数据
    } finally {
        loading.value = false
    }
}

// 获取卖家信息
const fetchSellerInfo = async (sellerId: number | string) => {
    if (!sellerId) return
    
    try {
        // 使用正确的API接口 /user/info 并传递userId参数
        const response = await request.get('/user/info', {
            params: { userId: sellerId }
        })
        console.log('获取卖家信息响应:', response)
        
        if (response && (response.code === 200 || response.status === 200)) {
            const userData = response.data || {}
            
            seller.value = {
                id: userData.id || sellerId,
                name: userData.nickname || userData.username || userData.name || '未知卖家',
                school: userData.school || userData.college || '',
                avatar: userData.avatar || userData.avatarUrl || 'https://picsum.photos/100/100',
                rating: userData.rating || 5
            }
        }
    } catch (error) {
        console.error('获取卖家信息出错:', error)
    }
}

// 更新商品数据的统一方法
const updateProductData = (productDetail: any) => {
    console.log('处理商品数据:', productDetail);
    
    // 尝试提取图片URL
    const imageUrls: string[] = []; // 明确类型
    
    // 检查所有可能的图片字段
    if (productDetail.mainImageUrl) imageUrls.push(productDetail.mainImageUrl);
    if (productDetail.image) imageUrls.push(productDetail.image);
    if (productDetail.imageUrl) imageUrls.push(productDetail.imageUrl);
    if (productDetail.coverImage) imageUrls.push(productDetail.coverImage);
    
    // 检查可能的图片数组
    if (productDetail.images && Array.isArray(productDetail.images)) {
        productDetail.images.forEach((img: any) => {
            if (typeof img === 'string') {
                imageUrls.push(img);
            } else if (img && typeof img === 'object') {
                const url = img.url || img.imageUrl || img.image_url || img.src || img.path || img.image;
                if (url) imageUrls.push(url);
            }
        });
    }
    
    // 基础商品信息
    product.value = {
        id: productDetail.id || 0,
        name: productDetail.name || '未知商品',
        price: productDetail.price || 0,
        originalPrice: productDetail.originalPrice || productDetail.original_price || 0,
        condition: productDetail.condition || '未知',
        status: (productDetail.status === 1 || productDetail.status === "在售" || productDetail.status === "selling") ? 'selling' : 
                (productDetail.status === 2 || productDetail.status === "已售" || productDetail.status === "sold") ? 'sold' :
                (productDetail.status === 3 || productDetail.status === "已下架" || productDetail.status === "off_shelf") ? 'off_shelf' : 'unknown',
        stock: productDetail.stock !== undefined ? productDetail.stock : 1, // 处理stock可能为0的情况
        description: productDetail.description || productDetail.content || productDetail.introduce || '暂无描述',
        // 使用提取的图片URL或默认图片
        images: imageUrls.length > 0 ? imageUrls : (productDetail.mainImageUrl ? [productDetail.mainImageUrl] : ['https://picsum.photos/800/600?random=1']),
        mainImageUrl: productDetail.mainImageUrl, // 确保 mainImageUrl 被赋值
        sellerId: productDetail.sellerId || (productDetail.seller ? productDetail.seller.id : undefined),
        categoryId: productDetail.categoryId || (productDetail.category ? productDetail.category.id : undefined),
        categoryName: productDetail.categoryName || (productDetail.category ? productDetail.category.name : undefined),
        locationDescription: productDetail.locationDescription,
        views: productDetail.views || 0,
        favoriteCount: productDetail.favoriteCount || 0,
        isFavorite: productDetail.isFavorite || false,
    };
    
    console.log('处理后的商品数据:', product.value);
    
    // 更新卖家信息
    if (productDetail.seller) {
        seller.value = {
            id: productDetail.seller.id || productDetail.sellerId || 0,
            name: productDetail.seller.name || productDetail.sellerName || '未知卖家',
            school: productDetail.seller.school || productDetail.school || '',
            avatar: productDetail.seller.avatar || 'https://picsum.photos/100/100',
            rating: productDetail.seller.rating || 5
        };
    } else {
        // 如果没有seller对象，尝试从productDetail中提取卖家信息
        seller.value = {
            id: productDetail.sellerId || 0,
            name: productDetail.sellerName || '未知卖家',
            school: productDetail.school || '',
            avatar: 'https://picsum.photos/100/100',
            rating: 5
        };
    }
    
    // 获取卖家详细信息
    if (productDetail.sellerId || (productDetail.seller && productDetail.seller.id)) {
        const sellerId = productDetail.sellerId || (productDetail.seller && productDetail.seller.id);
        fetchSellerInfo(sellerId);
    }
    
    // 即使已有图片，也尝试从API获取更多商品图片
    fetchProductImages(productDetail.id);
    
    // 尝试加载推荐商品
    fetchRecommendations(productDetail.id, productDetail.categoryId);
}

// 新增：从后端获取商品图片的方法
const fetchProductImages = async (productId: number) => {
    if (!productId) return
    
    try {
        const response = await request.get(`/products/${productId}/images`)
        console.log('获取商品图片响应:', response)
        
        if (response && response.data && Array.isArray(response.data)) {
            const images = response.data
            
            if (images.length > 0) {
                // 提取图片URL
                const imageUrls = images.map((img: any) => {
                    // 如果是字符串，直接返回
                    if (typeof img === 'string') return img;
                    // 如果是对象，尝试获取URL
                    return img.imageUrl || img.url || img.image || 
                           img.coverImage || img.imgUrl || img.src || img.path || 
                           (img.image ? img.image : null);
                }).filter((url: any) => url); // 过滤掉空值
                
                // 更新商品图片
                if (imageUrls.length > 0) {
                    product.value.images = imageUrls
                    console.log('商品图片已更新:', product.value.images)
                    return // 成功获取图片后返回
                }
            }
        }
        
        // 如果上面的尝试都失败了，检查商品对象本身是否有图片信息
        if (product.value.mainImageUrl) {
            product.value.images = [product.value.mainImageUrl];
            console.log('使用商品主图作为图片:', product.value.mainImageUrl);
            return;
        }
        
        
        console.warn('获取商品图片失败或数据为空，使用默认图片');
        // 使用默认图片
        product.value.images = ['https://picsum.photos/800/600?random=1'];
    } catch (error) {
        console.error('获取商品图片出错:', error);
        // 如果获取失败，确保至少有一张默认图片
        if (!product.value.images || product.value.images.length === 0) {
            product.value.images = ['https://picsum.photos/800/600?random=1'];
        }
    }
}

// 修改processProductImages方法，使其更完善
const processProductImages = (productDetail: any) => {
    const processedImages: string[] = [];
    // 尝试从images数组中获取图片
    if (productDetail.images && Array.isArray(productDetail.images) && productDetail.images.length > 0) {
        // 处理每个图片URL，添加前缀如果需要
        processedImages.push(...productDetail.images.map((img: string) => {
            if (img && !img.startsWith('http')) {
                return '/images/product/' + img;
            }
            return img;
        }));
    }
    
    // 如果images数组为空，尝试其他可能的图片字段
    if (processedImages.length === 0) {
        // 收集所有可能的图片URL
        const possibleImageUrls: string[] = [];
        if (productDetail.mainImageUrl) {
            if (!productDetail.mainImageUrl.startsWith('http')) {
                possibleImageUrls.push('/images/product/' + productDetail.mainImageUrl);
            } else {
                possibleImageUrls.push(productDetail.mainImageUrl);
            }
        }
        if (productDetail.imageUrl) {
            if (!productDetail.imageUrl.startsWith('http')) {
                possibleImageUrls.push('/images/product/' + productDetail.imageUrl);
            } else {
                possibleImageUrls.push(productDetail.imageUrl);
            }
        }
        if (productDetail.image) {
            if (!productDetail.image.startsWith('http')) {
                possibleImageUrls.push('/images/product/' + productDetail.image);
            } else {
                possibleImageUrls.push(productDetail.image);
            }
        }
        if (productDetail.coverImage) {
            if (!productDetail.coverImage.startsWith('http')) {
                possibleImageUrls.push('/images/product/' + productDetail.coverImage);
            } else {
                possibleImageUrls.push(productDetail.coverImage);
            }
        }
    
        // 添加收集的图片URL到处理后的数组
        processedImages.push(...possibleImageUrls);
    }
    
    // 仍然没有图片，使用占位图
    if (processedImages.length === 0) {
        processedImages.push('https://picsum.photos/800/600?random=1');
    }
    
    return processedImages;
}

// 获取推荐商品
const fetchRecommendations = async (productId: number, categoryId?: number) => {
    try {
        // 优先根据分类获取推荐
        const params: any = { limit: 8 } // 修改 limit 为 8
        if (categoryId) {
            params.categoryId = categoryId
        }
        // 如果需要，可以加入userId进行个性化推荐
        // const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        // if (userInfo.id) {
        //     params.userId = userInfo.id
        // }

        const response = await request.get('/products/recommendations', { params })
        console.log('获取推荐商品响应:', response)
        
        if (response && response.data && response.data.content && response.data.content.length > 0) { // 确保 content 有数据
            let recommendData = response.data.content
            // 过滤掉当前商品
            if (productId) {
                recommendData = recommendData.filter((item: RecommendationItem) => item.id !== productId)
            }
            recommendations.value = recommendData.slice(0, 8).map((item: any) => ({ // 修改 slice 为 8
                id: item.id,
                name: item.name,
                price: item.price,
                image: item.mainImageUrl || item.image || item.imageUrl || item.coverImage || item.imgUrl || 'https://picsum.photos/300/300?random=' + item.id 
            }))
            // 如果成功获取到推荐数据，直接返回
            if (recommendations.value.length > 0) return;
        }
        
        // 如果上面的API没有返回有效数据，或者返回数据不足，尝试获取同类别商品
        if (categoryId) {
            try {
                const categoryResponse = await request.get('/products', { 
                    params: { 
                        categoryId,
                        limit: 9, // 请求9条，以便过滤后仍有8条
                        page: 0 // 通常分类商品也需要分页
                    } 
                })
                console.log('同类别商品响应:', categoryResponse)
                
                if (categoryResponse && categoryResponse.data && categoryResponse.data.content && categoryResponse.data.content.length > 0) {
                    let categoryProducts = categoryResponse.data.content
                    // 过滤掉当前商品
                    if (productId) {
                        categoryProducts = categoryProducts.filter((item: RecommendationItem) => item.id !== productId)
                    }
                    if (categoryProducts.length > 0) {
                        recommendations.value = categoryProducts.slice(0, 8).map((item: any) => ({ // 修改 slice 为 8
                                id: item.id,
                                name: item.name,
                                price: item.price,
                            image: item.mainImageUrl || item.image || item.imageUrl || item.coverImage || item.imgUrl || 'https://picsum.photos/300/300?random=' + item.id
                            }))
                        // 如果成功获取到同类商品数据，直接返回
                        if (recommendations.value.length > 0) return;
                    }
                }
            } catch (categoryError) {
                console.error('获取同类别商品出错:', categoryError)
            }
        }
        
        // 如果所有API尝试都失败或数据不足，使用默认推荐
        console.warn('获取推荐商品数据为空或失败，使用默认推荐');
        useDefaultRecommendations() // 获取失败时使用默认推荐

    } catch (error) {
        console.error('获取推荐商品出错:', error)
        useDefaultRecommendations() // 异常时也使用默认推荐
    }
}

// 使用默认模拟数据
const useDefaultMockData = () => {
    const productId = Number(route.params.id) || 1
    
    product.value = {
        id: productId,
        name: '二手 MacBook Pro 2021 (模拟)',
    price: 9999.99,
    originalPrice: 12999,
    condition: '九成新',
    status: 'selling',
    stock: 1,
        description: '95新 MacBook Pro 2021款，M1芯片，16G内存，512G固态硬盘，充电不到100次，无磕碰，原装配件齐全。(此为模拟数据)',
        images: ['https://picsum.photos/800/600?random=1', 'https://picsum.photos/800/600?random=2', 'https://picsum.photos/800/600?random=3'],
        mainImageUrl: 'https://picsum.photos/800/600?random=1',
        sellerId: 0,
        sellerName: '模拟卖家',
        sellerAvatar: 'https://picsum.photos/100/100',
        categoryId: 1,
        categoryName: '电子产品',
        views: 100,
        favoriteCount: 10,
        isFavorite: false
    }
    
    seller.value = { // 更新模拟卖家信息
        id: 0,
        name: '张三 (模拟)',
        school: '北京大学 (模拟)',
    avatar: 'https://picsum.photos/100/100',
    rating: 4.5
    }
    
    useDefaultRecommendations()
}

// 使用默认推荐数据
const useDefaultRecommendations = () => {
    recommendations.value = [
    {
        id: 2,
        name: 'iPad Pro 2020 (默认)',
        price: 4999,
        image: 'https://picsum.photos/300/300?random=5'
    },
    {
        id: 3,
        name: 'AirPods Pro (默认)',
        price: 1299,
        image: 'https://picsum.photos/300/300?random=6'
    },
    {
        id: 4,
        name: 'Apple Watch S7 (默认)',
        price: 2999,
        image: 'https://picsum.photos/300/300?random=7'
    },
    {
        id: 5,
        name: 'Kindle Paperwhite 5 (默认)',
        price: 899,
        image: 'https://picsum.photos/300/300?random=8'
    },
    {
        id: 6,
        name: 'Sony WH-1000XM4 (默认)',
        price: 1799,
        image: 'https://picsum.photos/300/300?random=9'
    },
    {
        id: 7,
        name: 'Nintendo Switch (默认)',
        price: 2099,
        image: 'https://picsum.photos/300/300?random=10'
    },
    {
        id: 8,
        name: 'Logitech MX Master 3 (默认)',
        price: 599,
        image: 'https://picsum.photos/300/300?random=11'
    },
    {
        id: 9,
        name: 'Dell U2720QM Monitor (默认)',
        price: 3599,
        image: 'https://picsum.photos/300/300?random=12'
    }
    ]
}

// 组件加载时获取数据
onMounted(() => {
    // 先尝试从localStorage获取
    const loadedFromLocalStorage = loadProductDataFromLocalStorage()
    
    // 如果没有从localStorage获取到数据，则从API获取
    if (!loadedFromLocalStorage) {
        fetchProductData()
    }
})

const currentImage = computed(() => {
    return product.value.images[currentImageIndex.value]
})

// 方法
const openGallery = () => {
    // 实现画廊预览逻辑
}

const addToCart = async () => {
    try {
        // 从localStorage获取用户ID
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const userId = userInfo.id

        if (!userId) {
            ElMessage.warning('请先登录')
            router.push('/login')
            return
        }

        // 发送添加购物车请求
        const response = await request.post('/cart/add', {
            userId: userId,
            productId: product.value.id
        })
        
        console.log('添加购物车响应:', response)
        
        // 检查响应状态
        if (response && (response.code === 200 || response.status === 200)) {
    ElMessage({
        message: '已添加到购物车',
        type: 'success',
        customClass: 'cart-message'
    })
        } else {
            const message = response?.message || '添加购物车失败'
            ElMessage.warning(message)
        }
    } catch (error) {
        console.error('添加购物车出错:', error)
        ElMessage.error('添加购物车失败，请稍后重试')
    }
}

const buyNow = () => {
    console.log('点击立即购买按钮');
    
    if (!product.value || !product.value.id) {
        ElMessage.warning('商品信息不完整')
        return
    }
    
    // 先检查登录状态
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')
    
    if (!token || !userInfo) {
        console.log('用户未登录，显示登录提示');
        ElMessageBox.confirm(
            '请先登录后再购买',
            '提示',
            {
                confirmButtonText: '去登录',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            // 记录当前路径，登录后可以返回
            router.push(`/login?redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}`)
        }).catch(() => {})
        return
    }
    console.log('product.value.status:', product.value.status);
    // 商品已售出状态检查
    if (product.value.status !== 'selling') {
        ElMessage.warning('该商品已售出')
        return
    }
    
    // 显示订单创建弹窗
    orderDialogVisible.value = true;
    console.log('订单弹窗可见性:', orderDialogVisible.value);
}

const contactSeller = async () => {
    try {
        // 检查用户登录状态
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const userId = userInfo.id
        const token = localStorage.getItem('token')

        if (!userId || !token) {
            ElMessage.error('请先登录才能联系卖家')
            router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath))
            return
        }

        if (!seller.value || !seller.value.id) {
            ElMessage.error('无法获取卖家信息')
            return
        }

        // 使用固定的问候消息
        const message = "您好，我对这个商品很感兴趣，可以详细了解一下吗？"

        // 直接调用联系卖家API
        const response = await request.post(
            `/products/${product.value.id}/contact`,
            message,
            {
                headers: {
                    'Content-Type': 'text/plain',
                    'Authorization': `Bearer ${token}`
                }
            }
        )

        // 根据后端返回的错误码来判断
        if (!response) {
            ElMessage.error('网络异常，请稍后重试')
            return
        }
        
        // 只有当code为200时才视为成功
        if (response.code !== 200) {
            // 根据不同错误码显示不同错误信息
            switch (response.code) {
                case 400:
                    ElMessage.error(response.message || '请求参数错误')
                    break
                case 401:
                    ElMessage.error('用户未登录或登录已过期')
                    break
                case 403:
                    ElMessage.error('您没有权限联系该卖家')
                    break
                case 404:
                    ElMessage.error('商品或卖家不存在')
                    break
                case 409:
                    ElMessage.error(response.message || '不能联系自己')
                    break
                case 500:
                    ElMessage.error('服务器内部错误，请稍后重试')
                    break
                default:
                    // 始终优先使用后端返回的错误信息
                    ElMessage.error(response.message || `联系失败(${response.code})`)
            }
            return
        }

        // 联系成功，显示成功消息
        ElMessage.success(response.message || '已成功联系卖家')
        
        // 从后端响应中获取会话相关信息
        const responseData = response.data || {}
        
        // 跳转到聊天页面，使用后端返回的会话ID或对话相关信息
        if (responseData.conversationId || responseData.chatId) {
            router.push({
                path: '/chat',
                query: {
                    conversationId: responseData.conversationId || responseData.chatId,
                    sellerId: seller.value.id,
                    productId: product.value.id
                }
            })
        } else {
            // 如果后端没有返回会话ID，则使用用户ID跳转
            router.push({
                path: '/chat',
                query: {
                    partnerId: seller.value.id,
                    productId: product.value.id
                }
            })
        }
    } catch (error) {
        console.error('联系卖家出错:', error)
        ElMessage.error('联系卖家失败，请稍后重试')
    }
}

const followSeller = () => {
    // 实现关注卖家逻辑
}

const goToProduct = (productId: number) => {
    // 清除当前商品数据
    localStorage.removeItem('currentProductDetail')
    router.push(`/product/${productId}`)
}

// 处理订单创建完成
const handleOrderCreated = (order: any) => {
    ElMessage.success('订单创建成功!')
    // 跳转到用户中心的订单列表
    router.push('/user/center?menu=orders')
}
</script>

<style scoped>
.product-detail {
    max-width: 1200px;
    margin: 0 auto;
    padding: 40px 24px;
    font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", sans-serif;
}

.product-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 48px;
    margin-bottom: 64px;
}

/* 商品展示区 */
.product-gallery {
    position: sticky;
    top: 24px;
}

.main-image {
    position: relative;
    border-radius: 16px;
    overflow: hidden;
    background: #f5f5f7;
    margin-bottom: 16px;
    cursor: zoom-in;
}

.gallery-image {
    width: 100%;
    aspect-ratio: 4/3;
    transition: transform 0.3s ease;
}

.main-image:hover .gallery-image {
    transform: scale(1.05);
}

.zoom-hint {
    position: absolute;
    right: 16px;
    bottom: 16px;
    background: rgba(0, 0, 0, 0.6);
    color: white;
    padding: 8px 12px;
    border-radius: 20px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
    opacity: 0;
    transform: translateY(10px);
    transition: all 0.3s ease;
}

.main-image:hover .zoom-hint {
    opacity: 1;
    transform: translateY(0);
}

.thumbnail-nav {
    display: flex;
    gap: 12px;
    overflow-x: auto;
    padding: 4px;
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.thumbnail-nav::-webkit-scrollbar {
    display: none;
}

.thumbnail {
    flex: 0 0 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    opacity: 0.6;
    transition: all 0.3s ease;
}

.thumbnail:hover {
    opacity: 0.8;
}

.thumbnail.active {
    opacity: 1;
    box-shadow: 0 0 0 2px #007AFF;
}

/* 商品信息区 */
.product-info {
    padding: 24px;
}

.product-header {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 24px;
}

.product-title {
    font-size: 28px;
    font-weight: 600;
    color: #1d1d1f;
    margin: 0;
    letter-spacing: -0.5px;
    line-height: 1.2;
}

.condition-tag {
    margin-top: 4px;
}

.product-meta {
    display: flex;
    align-items: baseline;
    gap: 12px;
    margin-bottom: 20px;
}

.product-price {
    font-size: 32px;
    font-weight: 700;
    color: #007AFF;
}

.product-original-price {
    font-size: 16px;
    color: #86868b;
    text-decoration: line-through;
}

.status-section {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 24px;
}

.stock-info {
    color: #86868b;
    font-size: 14px;
}

.product-description {
    background: #f5f5f7;
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 24px;
}

.description-title {
    font-size: 18px;
    font-weight: 600;
    color: #1d1d1f;
    margin: 0 0 16px;
}

.product-description p {
    font-size: 15px;
    line-height: 1.5;
    color: #424245;
}

.product-description p.collapsed {
    max-height: 120px;
    overflow: hidden;
    mask-image: linear-gradient(to bottom, black 60%, transparent);
}

.show-more {
    margin-top: 16px;
    color: #007AFF;
    font-size: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 4px;
}

/* 卖家信息卡片 */
.seller-card {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(20px);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.seller-info {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
}

.seller-avatar {
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05);
}

.seller-details {
    flex: 1;
}

.seller-name {
    font-size: 16px;
    font-weight: 600;
    color: #1d1d1f;
    margin-bottom: 4px;
}

.seller-school {
    font-size: 14px;
    color: #86868b;
}

.seller-actions {
    display: flex;
    gap: 12px;
}

/* 购买操作区 */
.purchase-section {
    position: sticky;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(20px);
    border-radius: 16px;
    padding: 24px;
    margin: 0 -24px;
    box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.04);
    display: flex;
    align-items: center;
}

.action-buttons {
    flex: 1;
    display: flex;
    gap: 12px;
}

.add-to-cart,
.buy-now {
    flex: 1;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
}

.buy-now {
    background: linear-gradient(135deg, #007AFF, #00B4FF);
    border: none;
}

/* 推荐区域 */
.recommendations {
    margin-top: 64px;
}

.section-title {
    font-size: 24px;
    font-weight: 600;
    color: #1d1d1f;
    margin-bottom: 24px;
}

.recommendation-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 24px;
}

.recommendation-card {
    border-radius: 12px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
}

.recommendation-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.recommendation-card .el-image {
    width: 100%;
    aspect-ratio: 1;
}

.recommendation-info {
    padding: 16px;
}

.recommendation-name {
    font-size: 16px;
    font-weight: 500;
    color: #1d1d1f;
    margin-bottom: 8px;
}

.recommendation-price {
    font-size: 14px;
    color: #007AFF;
    font-weight: 600;
}

/* 购物车提示消息 */
:deep(.cart-message) {
    background: rgba(0, 0, 0, 0.8) !important;
    color: white !important;
    backdrop-filter: blur(20px);
    border-radius: 20px !important;
    padding: 12px 24px !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .product-container {
        grid-template-columns: 1fr;
        gap: 32px;
    }

    .product-gallery {
        position: static;
    }

    .purchase-section {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        margin: 0;
        border-radius: 20px 20px 0 0;
    }
}
</style>